import React, { useState, useCallback, useEffect } from 'react';
import styles from './index.less';
import { componentList } from '../DragList';
import { uuid } from '../DragList/util';

function CanvasArea() {
  const [list, setList] = useState([]);
  const [pageConfig,setPageConfig]=useState({})
  const postMessage = (data) => {
    console.log(data);
    document.getElementById('iframe-wrr').contentWindow.postMessage(data, '*');
  };
  const onItemClick = () => {
    console.log('onItemClick');
  };

  const onAddItem = useCallback(
    (data) => {
      const { index, isBefore, addId } = data;
      const newList = [...list];
      const addItem = componentList.find((item) => item.id === addId);
      const item = {
        ...addItem,
        cid: uuid(),
      };
      let addIndex = 0;
      if (isBefore) {
        if (index > 0) {
          addIndex = index - 1;
        } else {
          addIndex = 0;
        }
      } else {
        addIndex = index + 1;
      }
      console.log(index, isBefore, addId);
      newList.splice(addIndex, 0, item);
      setList([...newList]);
    },
    [list],
  );
  useEffect(() => {
    postMessage({
      type: 0,
      list,
    });
  }, [list]);
  const onMessage = (e) => {
    const { type } = e.data;
    switch (type) {
      case 0:
        postMessage({
          type: 0,
          list,
        });
        break;
      case 1:
        onItemClick(e.data);
        break;
      case 2:
        onAddItem(e.data);
        break;
     case 5:
         const config=e?.data?.list
         setPageConfig([...config])
        break;
      default:
        postMessage(list);
        break;
    }
  };

  useEffect(() => {
    window.addEventListener('message', onMessage);
    return () => {
      window.removeEventListener('message', onMessage);
    };
  }, [list]);
  return (
    <div className={styles.canvasArea}>
      <div className={styles.preViewHead}> </div>
      <div className={styles.pageConfigShow}>
        <code>{JSON.stringify(pageConfig)}</code>
      </div>
      <div className={styles.content}>
        <div className={styles.container}>
          <iframe
            id="iframe-wrr"
            frameBorder="0"
            width="100%"
            height="758"
            src="http://localhost:3000/"
          ></iframe>
        </div>
      </div>
    </div>
  );
}
export default CanvasArea;
